package com.example.zsr.mydownloadmanager;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by zhengshaorui on 2017/2/22.
 */

public class DownloadTask extends Thread{
    private static final String TAG = "zsr";


    public DownloadTask(){

    }
    private boolean isCompleted = false;
    private URL connectUrl;
    private File dir;
    private int blocksize,threadid;
    private int downloadLength = 0;
    private int threadcount;
    private int filelength;
    private String filename;
    public DownloadTask(URL connectUrl, File dir, String filename,int blocksize, int threadid,
                        int threadcount,int filelength){
        this.connectUrl = connectUrl;
        this.dir = dir;
        this.blocksize = blocksize;
        this.threadid = threadid;
        this.threadcount = threadcount;
        this.filelength = filelength;
        this.filename = filename;
    }
    @Override
    public void run() {
        RandomAccessFile raf = null;
        BufferedInputStream bis = null;
        HttpURLConnection con = null;
        try {
            con = (HttpURLConnection) connectUrl.openConnection();
            con.setRequestMethod("GET");
            con.setReadTimeout(5000);
            con.setConnectTimeout(5000);

            int startpos = blocksize * threadid; //开始位置
            int endpos = blocksize * (threadid+1) -1; //结束位置

            if (threadid == (threadcount -1)) endpos = filelength; //最后一个结尾，以文件的长度结尾
            //设置下载位置
            con.setRequestProperty("Range", "bytes="+startpos+"-"+endpos);
            Log.d(TAG, "range: "+startpos+" "+endpos);

            //设置文件的写入位置
            File file = new File(dir,filename);
            raf = new RandomAccessFile(file,"rwd");
            raf.seek(startpos);

            //读数据
            bis = new BufferedInputStream(con.getInputStream());
            byte[] bytes = new byte[1024*4];
            int len = -1;
            while( (len = bis.read(bytes)) !=-1 ){
                raf.write(bytes,0,len);
                downloadLength += len;
            }
            isCompleted = true;

            Log.d(TAG, "finish: "+downloadLength);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bis != null) try {
                bis.close();
                if (raf != null) raf.close();
             } catch (IOException e) {
                e.printStackTrace();
            }
            if (con != null) con.disconnect();
        }


        super.run();
    }


    public boolean isCompleted() {
        return isCompleted;
    }

    public int getDownloadLength(){
        return downloadLength;
    }
}
